package com.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author : gelianbin
 * @createDate : 2021/4/15
 */
public class ImageToBaseUtil {

    /**
     * 获取文件
     * @param path 本地目录
     * @return
     * @throws FileNotFoundException
     */
    private static File getFile(String path) throws FileNotFoundException {
        File dir = new File(path);
        if (!dir.exists()) {
            throw new FileNotFoundException(path);
        }
        return dir;
    }

    /**
     * 获取文件二进制数组
     * @param file
     * @return
     * @throws IOException
     */
    public static byte[] getFileBytes(File file) throws IOException {
        byte[] bytes = new byte[(int) file.length()];

        FileInputStream inputStream = new FileInputStream(file);
        inputStream.read(bytes);
        inputStream.close();

        return bytes;
    }

    /**
     * 文件二进制数组转为base64（image/png;base64,）
     * @param imgData 二进制数组
     * @return
     */

    public static String getImgBase64(byte[] imgData) {
        // 对字节数组进行Base64编码
        String result = "";
        if (imgData != null) {
            // 使用JDK自带的Base64架包
            byte[] baseByte = Base64.getEncoder().encode(imgData);
            result = new String(baseByte, StandardCharsets.UTF_8);
        }
        return result;
    }



}
